class Solution {
    public int robotSim(int[] commands, int[][] obstacles) {
        Set<Long> obstacleSet = new HashSet<>();
        for (int[] obstacle : obstacles) {
            obstacleSet.add(calcHash(obstacle[0], obstacle[1]));
        }
        int maxLength = 0;
        int x = 0;
        int y = 0;
        for (int i : commands) {
            if (i == -2) {
                direction = (direction + 3) % 4;
            } else if (i == -1) {
                direction = (direction + 1) % 4;
            } else {
                while (i > 0) {
                    int nextX = x + dx[direction];
                    int nextY = y + dy[direction];
                    if (obstacleSet.contains(calcHash(nextX, nextY))) {
                        break;
                    } else {
                        x = nextX;
                        y = nextY;
                        maxLength = Math.max(maxLength, x * x + y * y);
                        i--;
                    }
                }
            }
        }
        return maxLength;
    }
    private long calcHash(int x, int y) {
        // 直接用Objects.hash(x,y)不好使,会碰撞
        return (x + 30000) * 60000L + y + 30000;
    }
    //                            N, E, S, W 
    private int[] dx = new int[] {0, 1, 0,-1};
    private int[] dy = new int[] {1, 0,-1, 0};
    int direction = 0;
}
